<template>
  <div v-loading="loading" class="p-4 pos-relative">
    <el-tabs v-model="editableTabsValue" type="card" editable @edit="handleTabsEdit" @tab-change="handleTabChange">
      <el-tab-pane v-for="(item, ind) in editableTabs" :key="item.name" :label="item.title" :name="item.name" style="disp">
        <div v-loading="loading" class="block">
          <div class="task-block">
            <div class="block-title">新建任务</div>
            <el-form :ref="setFormRef(ind)" :model="item.taskForm" inline size="small" :rules="rules">
              <el-form-item label="任务名称" prop="loadExperimentName" label-width="70">
                <el-input v-model="item.taskForm.loadExperimentName" placeholder="请输入" style="width: 180px" :disabled="item.state !== '待创建'"
              /></el-form-item>
              <el-form-item label="载荷分类" prop="loadType" label-width="70">
                <el-select
                  v-model="item.taskForm.loadType"
                  clearable
                  style="width: 180px"
                  :disabled="item.state !== '待创建' || item.selectHistoryTask"
                  @change="getpageVersions(item.taskForm)"
                >
                  <el-option v-for="(el, index) in pageLoadTypes" :key="'name' + index" :label="el.label" :value="el.label" />
                </el-select>
              </el-form-item>
              <el-form-item label="阶段" prop="stage">
                <el-select
                  v-model="item.taskForm.stage"
                  clearable
                  style="width: 180px"
                  :disabled="item.state !== '待创建' || item.selectHistoryTask"
                  @change="getpageVersions(item.taskForm)"
                >
                  <el-option v-for="(el, index) in pageStages" :key="'stage' + index" :label="el.label" :value="el.label" />
                </el-select>
              </el-form-item>
              <el-form-item label="版本号" prop="loadcaseVersionId">
                <el-select
                  v-model="item.taskForm.loadcaseVersionId"
                  style="width: 180px"
                  clearable
                  :disabled="item.state !== '待创建' || item.selectHistoryTask"
                >
                  <el-option v-for="(el, index) in pageVersions" :key="'stage' + index" :label="el.label" :value="el.value" />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-checkbox v-model="item.selectHistoryTask" :disabled="item.state !== '待创建'" @change="handleCheckboxChange">
                  选择历史任务
                </el-checkbox>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" :disabled="item.state !== '待创建'" @click="handleCreate(ind)">创建</el-button>
                <el-button :disabled="item.state !== '待创建'" @click="handleReset(ind)">重置</el-button>
              </el-form-item>
            </el-form>
            <!-- <div v-if="item.selectHistoryTask" class="border border-solid border-#e4e4e4 pt3 w-310">
              <el-form ref="taskFormRef" v-model="item.historyTaskForm" inline size="small">
                <el-form-item label="任务名称" prop="loadExperimentName">
                  <el-input v-model="item.historyTaskForm.loadExperimentName" placeholder="请输入" style="width: 180px" :disabled="true" />
                </el-form-item>
                <el-form-item label="载荷分类" prop="loadType">
                  <el-select
                    v-model="item.historyTaskForm.loadType"
                    clearable
                    style="width: 180px"
                    :disabled="true"
                    @change="getpageVersions(item.historyTaskForm)"
                  >
                    <el-option v-for="(el, index) in pageLoadTypes" :key="'name' + index" :label="el.label" :value="el.label" />
                  </el-select>
                </el-form-item>
                <el-form-item label="阶段" prop="stage">
                  <el-select
                    v-model="item.historyTaskForm.stage"
                    clearable
                    style="width: 180px"
                    :disabled="true"
                    @change="getpageVersions(item.historyTaskForm)"
                  >
                    <el-option v-for="(el, index) in pageStages" :key="'stage' + index" :label="el.label" :value="el.label" />
                  </el-select>
                </el-form-item>
                <el-form-item label="版本号" prop="loadcaseVersionId">
                  <el-select v-model="item.historyTaskForm.loadcaseVersionId" style="width: 180px" clearable :disabled="true">
                    <el-option v-for="(el, index) in pageVersions" :key="'stage' + index" :label="el.label" :value="el.value" />
                  </el-select>
                </el-form-item>
                <el-form-item prop="loadcaseVersionId">
                  <el-button type="primary" :disabled="item.state !== '待确认'" @click="handleClickSure">确定</el-button>
                </el-form-item>
              </el-form>
            </div> -->
          </div>
          <div class="task-block mt-2">
            <div class="block-title">上传文件</div>
            <!-- 飞行垂向 -->
            <el-row v-if="item?.taskForm?.loadType === '飞行垂向'" :gutter="10">
              <el-col :span="12">
                <TaskUpload
                  key="1"
                  v-model="item.originalFileName"
                  :disabled="item.state !== '待开始'"
                  name="ORIGINAL_LOAD"
                  :load-experiment-id="item.id"
                  @update-file="updatedUploadFile('originalFileName')"
                />
                <TaskUpload
                  key="2"
                  v-model="item.elevatorHingeCoordinateSystemInformation"
                  :disabled="item.state !== '待开始'"
                  class="mt-2"
                  name="elevator_hinge_coordinate_system_information_7_2"
                  :load-experiment-id="item.id"
                  accept=".txt"
                  title="升降舵铰链坐标系信息"
                  @update-file="updatedUploadFile('elevatorHingeCoordinateSystemInformation')"
                />
              </el-col>
              <el-col :span="12">
                <TaskUpload
                  key="3"
                  v-model="item.nodeInformationFileName"
                  :disabled="item.state !== '待开始'"
                  name="NODE_INFO"
                  :load-experiment-id="item.id"
                  accept=".dat"
                  title="上传节点信息"
                  @update-file="updatedUploadFile('nodeInformationFileName')"
                />
                <TaskUpload
                  key="4"
                  v-model="item.nodeLoadNumberFileName"
                  :disabled="item.state !== '待开始'"
                  name="NODE_LOAD_NUMBER"
                  :load-experiment-id="item.id"
                  title="上传节点载荷编号"
                  class="mt-2"
                  accept=".txt"
                  @update-file="updatedUploadFile('nodeLoadNumberFileName')"
                />
              </el-col>
            </el-row>
            <!--飞行侧向 -->
            <el-row v-if="item?.taskForm?.loadType === '飞行侧向'" :gutter="10">
              <el-col :span="12">
                <TaskUpload
                  key="1"
                  v-model="item.originalFileName"
                  :disabled="item.state !== '待开始'"
                  name="ORIGINAL_LOAD"
                  :load-experiment-id="item.id"
                  @update-file="updatedUploadFile('originalFileName')"
                />
                <TaskUpload
                  key="2"
                  v-model="item.directionalRudderCoordinateSystemInformation"
                  :disabled="item.state !== '待开始'"
                  class="mt-2"
                  name="DIRECTIONAL_RUDDER_COORDINATE_SYSTEM_INFORMATION_7_2"
                  :load-experiment-id="item.id"
                  accept=".txt"
                  title="方向舵铰链坐标系信息"
                  @update-file="updatedUploadFile('directionalRudderCoordinateSystemInformation')"
                />
              </el-col>
              <el-col :span="12">
                <TaskUpload
                  key="3"
                  v-model="item.nodeInformationFileName"
                  :disabled="item.state !== '待开始'"
                  name="NODE_INFO"
                  :load-experiment-id="item.id"
                  accept=".dat"
                  title="上传节点信息"
                  @update-file="updatedUploadFile('nodeInformationFileName')"
                />
                <TaskUpload
                  key="4"
                  v-model="item.nodeLoadNumberFileName"
                  :disabled="item.state !== '待开始'"
                  name="NODE_LOAD_NUMBER"
                  :load-experiment-id="item.id"
                  title="上传节点载荷编号"
                  class="mt-2"
                  accept=".txt"
                  @update-file="updatedUploadFile('nodeLoadNumberFileName')"
                />
              </el-col>
            </el-row>
            <!-- 地面载荷、动突风、动着陆 -->
            <el-row
              v-else-if="item?.taskForm?.loadType === '地面载荷' || item?.taskForm?.loadType === '动突风' || item?.taskForm?.loadType === '动着陆'"
              :gutter="10"
            >
              <el-col :span="12">
                <TaskUpload
                  key="5"
                  v-model="item.originalFileName"
                  :disabled="item.state !== '待开始'"
                  name="ORIGINAL_LOAD"
                  :load-experiment-id="item.id"
                  @update-file="updatedUploadFile('originalFileName')"
                />
                <TaskUpload
                  key="6"
                  v-model="item.cumulativeResult1G"
                  :disabled="item.state !== '待开始'"
                  class="mt-2"
                  name="CUMULATIVE_RESULT_1G"
                  :load-experiment-id="item.id"
                  accept=".txt"
                  title="1g累计结果"
                  @update-file="updatedUploadFile('cumulativeResult1G')"
                />
              </el-col>
              <el-col :span="12">
                <TaskUpload
                  key="7"
                  v-model="item.nodeInformationFileName"
                  :disabled="item.state !== '待开始'"
                  name="NODE_INFO"
                  :load-experiment-id="item.id"
                  accept=".dat"
                  title="上传节点信息"
                  @update-file="updatedUploadFile('nodeInformationFileName')"
                />
                <TaskUpload
                  key="8"
                  v-model="item.nodeLoadNumberFileName"
                  :disabled="item.state !== '待开始'"
                  name="NODE_LOAD_NUMBER"
                  :load-experiment-id="item.id"
                  title="上传节点载荷编号"
                  class="mt-2"
                  accept=".txt"
                  @update-file="updatedUploadFile('nodeLoadNumberFileName')"
                />
              </el-col>
            </el-row>
            <!-- 着路1g、突风1g、动滑行 -->
            <el-row v-else :gutter="10">
              <el-col :span="12">
                <TaskUpload
                  key="9"
                  v-model="item.originalFileName"
                  :disabled="item.state !== '待开始'"
                  height="267px"
                  name="ORIGINAL_LOAD"
                  :load-experiment-id="item.id"
                  @update-file="updatedUploadFile('originalFileName')"
                />
              </el-col>
              <el-col :span="12">
                <TaskUpload
                  key="10"
                  v-model="item.nodeInformationFileName"
                  :disabled="item.state !== '待开始'"
                  name="NODE_INFO"
                  :load-experiment-id="item.id"
                  accept=".dat"
                  title="上传节点信息"
                  @update-file="updatedUploadFile('nodeInformationFileName')"
                />
                <TaskUpload
                  key="11"
                  v-model="item.nodeLoadNumberFileName"
                  :disabled="item.state !== '待开始'"
                  name="NODE_LOAD_NUMBER"
                  :load-experiment-id="item.id"
                  title="上传节点载荷编号"
                  class="mt-2"
                  accept=".txt"
                  @update-file="updatedUploadFile('nodeLoadNumberFileName')"
                />
              </el-col>
            </el-row>
          </div>
          <div class="mt-2 mb-2">
            <el-button type="primary" size="small" :disabled="item.state === '运行中' || item.state === '待创建'" @click="handleStartTask">
              开始任务
            </el-button>
            <el-button type="primary" size="small" :disabled="item.state !== '运行中'" @click="handlePauseTask">暂停</el-button>
            <el-button type="primary" size="small" :disabled="item.state !== '运行中'" @click="handleStopTask">终止</el-button>
          </div>
          <div class="task-block">
            <div class="block-title">处理进度<el-button class="m-l-4" type="text" @click="handleRunLog">运行日志</el-button></div>
            <el-row
              v-if="item?.taskForm?.loadType === '动突风' || item?.taskForm?.loadType === '动着陆' || item?.taskForm?.loadType === '动滑行'"
              :gutter="10"
            >
              <el-col :span="12">
                <ProgressBlock key="5" title="第一步：载荷筛选" :percentage="item.percentage2" :datas="item.stepData2" />
              </el-col>
              <el-col :span="12">
                <ProgressBlock key="5" title="第二步：载荷分载" :percentage="item.percentage3" :datas="item.stepData3" />
              </el-col>
            </el-row>
            <el-row v-else :gutter="10">
              <el-col :span="8">
                <ProgressBlock key="1" title="第一步：载荷数据检查" :percentage="item.percentage1" :datas="item.stepData1" />
              </el-col>
              <el-col :span="8">
                <ProgressBlock key="2" title="第二步：载荷筛选" :percentage="item.percentage2" :datas="item.stepData2" />
              </el-col>
              <el-col :span="8">
                <ProgressBlock key="3" title="第三步：载荷分载" :percentage="item.percentage3" :datas="item.stepData3" />
              </el-col>
            </el-row>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>

    <div v-if="!editableTabs.length" class="no-data">
      <el-empty>
        <el-button type="primary" size="small" @click="handleAdd">创建实验</el-button>
      </el-empty>
    </div>
    <el-dialog v-if="editDialogShow" v-model="editDialogShow" title="输入实验名称" width="500px">
      <el-input v-model="tabTitleValue" placeholder="请输入" />
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleEditSure">确定</el-button>
          <el-button @click="handleEditClose">取消</el-button>
        </div>
      </template>
    </el-dialog>
    <TaskSelectDialog ref="taskSelectDialogRef" @on-sure="handleTaskSelectDialogSure" />
    <RunLogDialog ref="runLogDialogRef" />
  </div>
</template>

<script setup name="loadTaskSubmission" lang="ts">
import TaskUpload from './taskUpload.vue';
import ProgressBlock from './progressBlock.vue';
import { TabPaneName } from 'element-plus';
import { getAlgorithmList } from '@/api/loadProcessingAlgorithm/loadAlgorithmManagement/index';
import { getVersionList } from '@/api/loadProcessingAlgorithm/loadVersionManagement/index';
import {
  addExperiment,
  editExperiment,
  getExperimentDetail,
  startTask,
  getTaskInfoList,
  getExperimentList,
  addByHistory,
  taskLogList
} from '@/api/loadProcessingAlgorithm/loadTaskManagement/index';
import { loadNames, stages } from '@/api/loadProcessingAlgorithm/index';
import TaskSelectDialog from './taskSelectDialog';
import RunLogDialog from './runLogDialog.vue';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const route = useRoute();
const editableTabsValue = ref(0);
const taskFormRefs = ref<ElFormInstance[]>([]);
const taskSelectDialogRef = ref();
const runLogDialogRef = ref();
const tabTitleValue = ref('');
const timer = ref(null);
const loading = ref(true);
const contentForm = reactive({
  id: '',
  title: '载荷实验',
  name: 0,
  taskForm: {
    loadcaseVersionId: '',
    loadType: '',
    loadExperimentName: '',
    stage: '',
    state: '待开始'
  },
  historyTaskForm: {
    loadcaseVersionId: '',
    loadType: '',
    loadExperimentName: '',
    stage: '',
    state: '待开始'
  },
  state: '待创建',
  historyLoadExperimentId: '',
  selectHistoryTask: false,
  originalFileName: '',
  nodeInformationFileName: '',
  nodeLoadNumberFileName: '',
  cumulativeResult1G: '',
  directionalRudderCoordinateSystemInformation: '',
  elevatorHingeCoordinateSystemInformation: '',
  stepData1: [],
  stepData2: [],
  stepData3: [],
  percentage1: 0,
  percentage2: 0,
  percentage3: 0
});
const pauseStep = ref(0);
const pauseNumber = ref(0);
const oldExperimentData = ref();
const rules = reactive({
  loadcaseVersionId: [{ required: true, message: '版本号不能为空', trigger: 'change' }],
  loadType: [{ required: true, message: '载荷分类不能为空', trigger: 'change' }],
  loadExperimentName: [{ required: true, message: '任务名称不能为空', trigger: 'blur' }],
  stage: [{ required: true, message: '阶段不能为空', trigger: 'change' }]
});
const editableTabs = ref([]);
const editDialogShow = ref(false);
const pageLoadTypes = ref([]);
const pageStages = ref(stages);
const pageVersions = ref([]);
const handleTabsEdit = async (targetName: TabPaneName | undefined, action: 'remove' | 'add') => {
  if (action === 'add') {
    if (editableTabs.value.length < 5) {
      handleAdd();
      if (timer.value) {
        clearInterval(timer.value);
      }
    } else {
      proxy?.$modal.msgWarning('最多创建5个实验！');
    }
  } else {
    await proxy?.$modal.confirm('是否确认关闭该实验?');
    const index = Number(targetName);
    editableTabs.value.splice(index, 1);
    if (editableTabsValue.value === index) {
      editableTabsValue.value = index > 0 ? index - 1 : editableTabs.value.length > 0 ? index + 1 : null;
    }
  }
};
const handleAdd = () => {
  tabTitleValue.value = '';
  editDialogShow.value = true;
};
const handleEditSure = () => {
  if (!tabTitleValue.value) {
    proxy?.$modal.msgWarning('请输入实验名称！');
    return false;
  }
  const obj = JSON.parse(JSON.stringify(contentForm));
  obj.title = tabTitleValue.value;
  obj.taskForm.loadExperimentName = tabTitleValue.value;
  obj.name = editableTabs.value.length;
  editableTabs.value.push(obj);
  editableTabsValue.value = obj.name;
  handleEditClose();
};
const handleEditClose = () => {
  editDialogShow.value = false;
};
const getPageLoadTypes = () => {
  loadNames.forEach((item) => {
    pageLoadTypes.value = [...pageLoadTypes.value, ...item.children];
  });
};
const getpageVersions = async (data) => {
  if (data.loadType && data.stage) {
    const obj = {
      pageNum: 1,
      pageSize: 99,
      loadType: data.loadType,
      stage: data.stage,
      state: '使用中'
    };
    const res = await getVersionList(obj);
    if (!res?.rows?.length) {
      data.loadcaseVersionId = '';
      pageVersions.value = [];
      return false;
    }
    pageVersions.value = res?.rows?.map((item) => {
      return {
        value: item.id,
        label: item.version
      };
    });
  } else {
    data.loadcaseVersionId = '';
  }
};
const setFormRef = (index) => {
  return (el) => {
    if (el) {
      taskFormRefs.value[index] = el;
    }
  };
};
const getAlgorithms = async (step, loadType) => {
  const obj = {
    step: step,
    loadType: loadType,
    pageNum: 1,
    pageSize: 99
  };
  const res = await getAlgorithmList(obj);
  return res.rows.map((item) => {
    return {
      percentage: 0,
      algorithmName: item.algorithmName,
      indeterminate: false,
      orderNumber: item.orderNumber,
      step: item.step,
      id: item.id,
      status: ''
    };
  });
};
const handleCreate1 = async (index) => {
  const el = taskFormRefs.value[index];
  await el.validate(async (valid, fields) => {
    if (valid) {
      const obj = editableTabs.value[editableTabsValue.value];
      obj.state = '待开始';
      const res = await addExperiment(obj.taskForm).catch(() => {
        obj.state = '待创建';
      });
      obj.id = res.data;
      obj.stepData1 = await getAlgorithms(1, obj.taskForm.loadType);
      obj.stepData2 = await getAlgorithms(2, obj.taskForm.loadType);
      obj.stepData3 = await getAlgorithms(3, obj.taskForm.loadType);
      proxy?.$modal.msgSuccess('创建成功！');
    } else {
      proxy?.$modal.msgError('请填写完成信息！');
    }
  });
};
const updatedPercentage = (obj) => {
  obj.percentage1 = 100;
  obj.stepData1.forEach((el) => {
    el.indeterminate = false;
    el.percentage = 100;
  });
  obj.percentage2 = 100;
  obj.stepData2.forEach((el) => {
    el.indeterminate = false;
    el.percentage = 100;
  });
};

const handleCreate2 = async (index) => {
  const el = taskFormRefs.value[index];
  await el.validate(async (valid: any) => {
    if (valid) {
      const obj = editableTabs.value[editableTabsValue.value];
      if (obj.taskForm.loadExperimentName === oldExperimentData.value.loadExperimentName) {
        proxy?.$modal.msgWarning('任务名称与历史任务名称一致，请重新填写！');
        return false;
      }
      obj.state = '待开始';
      const newObj = {
        loadcaseVersionId: obj.taskForm.loadcaseVersionId,
        loadExperimentName: obj.taskForm.loadExperimentName,
        loadType: obj.taskForm.loadType,
        stage: obj.taskForm.stage,
        originalFileName: obj.originalFileName,
        cumulativeResult1G: obj.cumulativeResult1G,
        nodeInformationFileName: obj.nodeInformationFileName,
        nodeLoadNumberFileName: obj.nodeLoadNumberFileName,
        directionalRudderCoordinateSystemInformation: obj.directionalRudderCoordinateSystemInformation,
        elevatorHingeCoordinateSystemInformation: obj.elevatorHingeCoordinateSystemInformation,
        historyLoadExperimentId: obj.historyLoadExperimentId,
        state: obj.state
      };
      const res = await addByHistory(newObj).catch(() => {
        obj.state = '待创建';
      });
      obj.id = res.data;
      obj.stepData1 = await getAlgorithms(1, obj.taskForm.loadType);
      obj.stepData2 = await getAlgorithms(2, obj.taskForm.loadType);
      obj.stepData3 = await getAlgorithms(3, obj.taskForm.loadType);
      updatedPercentage(obj);
      proxy?.$modal.msgSuccess('创建成功！');
    } else {
      proxy?.$modal.msgError('请填写完成信息！');
    }
  });
};
const handleCreate = async (index) => {
  const obj = editableTabs.value[editableTabsValue.value];
  if (!obj.selectHistoryTask) {
    handleCreate1(index);
  } else {
    handleCreate2(index);
  }
};
const handleReset = (index) => {
  const el = taskFormRefs.value[index];
  el.resetFields();
};
// const getLog = async (data, step, orderNumber) => {
//   const obj = {
//     loadExperimentId: data.id,
//     // step: step,
//     // orderNumber: orderNumber
//   };
//   const res = await taskLogList(obj);
//   return res.rows;
// };
const setStepData1 = (data, obj) => {
  if (data.stepData1.length !== obj.orderNumber) {
    if (data.percentage1 < 90) {
      // data.percentage1 += 10;
      data.percentage1 = Number(Number((obj.orderNumber / data.stepData1.length) * 100).toFixed(2));
    }
  } else {
    if (obj.state === '已完成') {
      data.percentage1 = 100;
    } else {
      data.percentage1 = 95;
    }
  }
  let flag = 0; //0 运行中 1已完成 2运行错误 3已暂停 4已终止
  data.stepData1.forEach(async (el, index) => {
    if (el.orderNumber < obj.orderNumber) {
      el.indeterminate = false;
      el.percentage = 100;
    } else if (el.orderNumber === obj.orderNumber) {
      if (obj.state === '已完成') {
        el.indeterminate = false;
        el.percentage = 100;
        flag = 1;
      } else if (obj.state === '运行错误') {
        el.indeterminate = false;
        el.percentage = 0;
        el.status = 'exception';
        // const result = await getLog(data, 1, index);
        // if (result.length) {
        //   el.log = result[0].log;
        // }
        flag = 2;
      } else if (obj.state === '已暂停') {
        el.indeterminate = false;
        el.percentage = 0;
        flag = 3;
        pauseStep.value = 1;
        pauseNumber.value = index;
      } else if (obj.state === '已终止') {
        el.indeterminate = false;
        el.percentage = 100;
        flag = 4;
      } else {
        el.indeterminate = true;
        el.percentage = 50;
        flag = 0;
      }
    }
  });
  return flag;
};
const setStepData2 = (data, obj) => {
  data.percentage1 = 100;
  data.stepData1.forEach((el) => {
    el.indeterminate = false;
    el.percentage = 100;
  });
  if (data.stepData2.length !== obj.orderNumber) {
    if (data.percentage2 < 99) {
      data.percentage2 = Number(Number((obj.orderNumber / data.stepData2.length) * 100).toFixed(2));
    }
  } else {
    if (obj.state === '已完成') {
      data.percentage2 = 100;
    } else {
      data.percentage2 = 95;
    }
  }
  let flag = 0;
  data.stepData2.forEach(async (el, index) => {
    if (el.orderNumber < obj.orderNumber) {
      el.indeterminate = false;
      el.percentage = 100;
    } else if (el.orderNumber === obj.orderNumber) {
      if (obj.state === '已完成') {
        el.indeterminate = false;
        el.percentage = 100;
        flag = 1;
      } else if (obj.state === '运行错误') {
        el.indeterminate = false;
        el.percentage = 0;
        el.status = 'exception';
        flag = 2;
      } else if (obj.state === '已暂停') {
        el.indeterminate = false;
        el.percentage = 0;
        // const result = await getLog(data, 2, index);
        // if (result.length) {
        //   el.log = result[0].log;
        // }
        flag = 3;
        pauseStep.value = 2;
        pauseNumber.value = index;
      } else if (obj.state === '已终止') {
        el.indeterminate = false;
        el.percentage = 100;
        flag = 4;
      } else {
        el.indeterminate = true;
        el.percentage = 50;
        flag = 0;
      }
    }
  });
  return flag;
};
const setStepData3 = (data, obj) => {
  // data.percentage1 = 100;
  // data.stepData1.forEach((el) => {
  //   el.indeterminate = false;
  //   el.percentage = 100;
  // });
  // data.percentage2 = 100;
  // data.stepData2.forEach((el) => {
  //   el.indeterminate = false;
  //   el.percentage = 100;
  // });
  updatedPercentage(data);
  if (data.stepData3.length !== obj.orderNumber) {
    if (data.percentage3 < 99) {
      data.percentage3 = Number(Number((obj.orderNumber / data.stepData3.length) * 100).toFixed(2));
    }
  } else {
    if (obj.state === '已完成') {
      data.percentage3 = 100;
    } else {
      data.percentage3 = 95;
    }
  }
  let flag = 0;
  data.stepData3.forEach(async (el, index) => {
    if (el.orderNumber < obj.orderNumber) {
      el.indeterminate = false;
      el.percentage = 100;
    } else if (el.orderNumber === obj.orderNumber) {
      if (obj.state === '已完成') {
        el.indeterminate = false;
        el.percentage = 100;
        flag = 1;
        if (obj.orderNumber === data.stepData3.length && timer.value) {
          clearInterval(timer.value);
        }
      } else if (obj.state === '运行错误') {
        el.indeterminate = false;
        el.percentage = 0;
        el.status = 'exception';
        // const result = await getLog(data, 3, index);
        // if (result.length) {
        //   el.log = result[0].log;
        // }
        flag = 2;
      } else if (obj.state === '已暂停') {
        el.indeterminate = false;
        el.percentage = 0;
        flag = 3;
        pauseStep.value = 3;
        pauseNumber.value = index;
      } else if (obj.state === '已终止') {
        el.indeterminate = false;
        el.percentage = 100;
        flag = 4;
      } else {
        el.indeterminate = true;
        el.percentage = 50;
        flag = 0;
      }
    }
  });
  return flag;
};
//修改任务条
const updateProgress = async () => {
  const data = editableTabs.value[Number(editableTabsValue.value)];
  if (data.state === '待开始') {
    return false;
  }
  const obj = {
    loadExperimentId: data.id,
    pageSize: 99,
    pageNum: 1
  };
  const res = await getTaskInfoList(obj);
  const datas = res.rows;
  let flag = 0;
  if (datas.length) {
    const item = datas[0];
    switch (item.step) {
      case 1:
        flag = setStepData1(data, item);
        break;
      case 2:
        flag = setStepData2(data, item);
        break;
      case 3:
        flag = setStepData3(data, item);
        break;
      default:
        break;
    }
  }
  return flag;
};
const updatedUploadFile = async (name) => {
  const obj = editableTabs.value[Number(editableTabsValue.value)];
  const newObj = {
    id: obj.id,
    loadcaseVersionId: obj.taskForm.loadcaseVersionId,
    loadType: obj.taskForm.loadType,
    loadExperimentName: obj.taskForm.loadExperimentName,
    stage: obj.taskForm.stage,
    state: '待开始'
  };
  newObj[name] = obj[name];
  await editExperiment(newObj); // 保存上传文件
};
const clearProgress = (obj) => {
  obj.percentage1 = 0;
  obj.percentage2 = 0;
  obj.percentage3 = 0;
  obj.stepData1.forEach((el) => {
    el.indeterminate = false;
    el.percentage = 0;
    el.status = '';
  });
  obj.stepData2.forEach((el) => {
    el.indeterminate = false;
    el.percentage = 0;
    el.status = '';
  });
  obj.stepData3.forEach((el) => {
    el.indeterminate = false;
    el.percentage = 0;
    el.status = '';
  });
};
const clearProgress2 = (obj) => {
  obj.percentage1 = 100;
  obj.percentage2 = 100;
  obj.percentage3 = 0;
  obj.stepData1.forEach((el) => {
    el.indeterminate = false;
    el.percentage = 100;
    el.status = '';
  });
  obj.stepData2.forEach((el) => {
    el.indeterminate = false;
    el.percentage = 100;
    el.status = '';
  });
  obj.stepData3.forEach((el) => {
    el.indeterminate = false;
    el.percentage = 0;
    el.status = '';
  });
};
const updateTimer = (obj) => {
  if (timer.value) {
    clearInterval(timer.value);
  }
  timer.value = setInterval(async () => {
    const flag = await updateProgress();
    // if (!flag) {
    //   clearInterval(timer.value);
    //   proxy?.$modal.msgError('运行错误！');
    // }
    switch (flag) {
      case 2:
        obj.state = '运行错误';
        proxy?.$modal.msg('运行错误！');
        break;
      case 3:
        obj.state = '已暂停';
        proxy?.$modal.msg('已暂停');
        clearInterval(timer.value);
        break;
      case 4:
        obj.state = '已终止';
        proxy?.$modal.msg('已终止');
        clearInterval(timer.value);
        break;
      default:
        break;
    }
  }, 1000);
};
const handleStartTask1 = async (obj) => {
  if (obj.state !== '已暂停') {
    const stepbj = obj.stepData1[0];
    const newObj2 = {
      loadExperimentId: obj.id,
      loadType: obj.taskForm.loadType,
      step: stepbj.step,
      orderNumber: stepbj.orderNumber,
      algorithmName: stepbj.algorithmName,
      state: '运行中'
    };
    await startTask(newObj2); // 开始任务
    clearProgress(obj);
    obj.state = '运行中';
    updateTimer(obj);
  } else {
    let stepbj = obj.stepData1[pauseNumber.value];
    if (pauseStep.value === 1) {
      stepbj = obj.stepData1[pauseNumber.value];
    } else if (pauseStep.value === 2) {
      stepbj = obj.stepData3[pauseNumber.value];
    } else {
      stepbj = obj.stepData3[pauseNumber.value];
    }
    const newObj2 = {
      loadExperimentId: obj.id,
      loadType: obj.taskForm.loadType,
      step: stepbj.step,
      orderNumber: stepbj.orderNumber,
      algorithmName: stepbj.algorithmName,
      state: '运行中'
    };
    await startTask(newObj2); // 开始任务
    obj.state = '运行中';
    updateTimer(obj);
  }
};

const handleStartTask2 = async (obj) => {
  if (obj.state !== '已暂停') {
    const stepbj = obj.stepData3[0];
    const newObj2 = {
      loadExperimentId: obj.id,
      loadType: obj.taskForm.loadType,
      step: stepbj.step,
      orderNumber: stepbj.orderNumber,
      algorithmName: stepbj.algorithmName,
      state: '运行中'
    };
    await startTask(newObj2); // 开始任务
    clearProgress2(obj);
    obj.state = '运行中';
    updateTimer(obj);
  } else {
    const stepbj = obj.stepData3[pauseNumber.value];
    const newObj2 = {
      loadExperimentId: obj.id,
      loadType: obj.taskForm.loadType,
      step: stepbj.step,
      orderNumber: stepbj.orderNumber,
      algorithmName: stepbj.algorithmName,
      state: '运行中'
    };
    await startTask(newObj2); // 开始任务
    obj.state = '运行中';
    updateTimer(obj);
  }
};
const handleStartTask = async () => {
  const obj = editableTabs.value[Number(editableTabsValue.value)];
  if (!obj.selectHistoryTask) {
    handleStartTask1(obj);
  } else {
    handleStartTask2(obj);
  }
};
const setHistoryTask = async (obj, datas) => {
  if (datas.historyLoadExperimentId) {
    const res = await getExperimentDetail(String(datas.historyLoadExperimentId));
    const newDatas = res.data;
    oldExperimentData.value = newDatas;
    obj.historyTaskForm.loadcaseVersionId = newDatas.loadcaseVersionId;
    obj.historyTaskForm.loadType = newDatas.loadType;
    obj.historyTaskForm.loadExperimentName = newDatas.loadExperimentName;
    obj.historyTaskForm.stage = newDatas.stage;
    updatedPercentage(obj);
  }
};
const setData = async (id) => {
  const res = await getExperimentDetail(String(id));
  const datas = res.data;
  const obj = {
    id: datas.id,
    title: datas.loadExperimentName,
    name: 0,
    taskForm: {
      loadcaseVersionId: datas.loadcaseVersionId,
      loadType: datas.loadType,
      loadExperimentName: datas.loadExperimentName,
      stage: datas.stage,
      state: datas.state
    },
    historyTaskForm: {
      loadcaseVersionId: '',
      loadType: '',
      loadExperimentName: '',
      stage: '',
      state: '待创建'
    },
    state: datas.state,
    historyLoadExperimentId: datas.historyLoadExperimentId,
    selectHistoryTask: Boolean(datas.historyLoadExperimentId),
    originalFileName: datas.originalFileName,
    cumulativeResult1G: datas.cumulativeResult1G,
    nodeInformationFileName: datas.nodeInformationFileName,
    nodeLoadNumberFileName: datas.nodeLoadNumberFileName,
    directionalRudderCoordinateSystemInformation: datas.directionalRudderCoordinateSystemInformation,
    elevatorHingeCoordinateSystemInformation: datas.elevatorHingeCoordinateSystemInformation,
    stepData1: [],
    stepData2: [],
    stepData3: [],
    percentage1: 0,
    percentage2: 0,
    percentage3: 0
  };
  setHistoryTask(obj, datas);
  obj.stepData1 = await getAlgorithms(1, obj.taskForm.loadType);
  obj.stepData2 = await getAlgorithms(2, obj.taskForm.loadType);
  obj.stepData3 = await getAlgorithms(3, obj.taskForm.loadType);
  editableTabs.value = [obj];
  getpageVersions(obj.taskForm);
  if (obj.state !== '运行中') {
    updateProgress();
  } else {
    updateTimer(obj);
  }
};
const setDatas = (arr) => {
  editableTabs.value = [];
  arr.forEach(async (item, index) => {
    const res = await getExperimentDetail(String(item.id));
    const datas = res.data;
    const obj = {
      id: datas.id,
      title: datas.loadExperimentName,
      name: index,
      taskForm: {
        loadcaseVersionId: datas.loadcaseVersionId,
        loadType: datas.loadType,
        loadExperimentName: datas.loadExperimentName,
        stage: datas.stage,
        state: datas.state
      },
      historyTaskForm: {
        loadcaseVersionId: '',
        loadType: '',
        loadExperimentName: '',
        stage: '',
        state: '待开始'
      },
      state: datas.state,
      historyLoadExperimentId: datas.historyLoadExperimentId,
      selectHistoryTask: Boolean(datas.historyLoadExperimentId),
      originalFileName: datas.originalFileName,
      cumulativeResult1G: datas.cumulativeResult1G,
      nodeInformationFileName: datas.nodeInformationFileName,
      nodeLoadNumberFileName: datas.nodeLoadNumberFileName,
      directionalRudderCoordinateSystemInformation: datas.directionalRudderCoordinateSystemInformation,
      elevatorHingeCoordinateSystemInformation: datas.elevatorHingeCoordinateSystemInformation,
      stepData1: [],
      stepData2: [],
      stepData3: [],
      percentage1: 0,
      percentage2: 0,
      percentage3: 0
    };
    setHistoryTask(obj, datas);
    obj.stepData1 = await getAlgorithms(1, obj.taskForm.loadType);
    obj.stepData2 = await getAlgorithms(2, obj.taskForm.loadType);
    obj.stepData3 = await getAlgorithms(3, obj.taskForm.loadType);
    editableTabs.value.push(obj);
    getpageVersions(obj.taskForm);
    if (obj.state !== '运行中') {
      updateProgress();
    } else {
      updateTimer(obj);
    }
  });
};
const handleTabChange = (targetName: TabPaneName) => {
  const obj = editableTabs.value[Number(targetName)];
  if (timer.value) {
    clearInterval(timer.value);
  }
  if (obj.state !== '运行中') {
    updateProgress();
  } else {
    updateTimer(obj);
  }
};
const initData = async () => {
  loading.value = true;
  const id = route.query.id;
  if (id) {
    setData(id);
    loading.value = false;
    return false;
  }
  const obj = {
    state: '运行中',
    pageNum: 1,
    pageSize: 5
  };
  const res = await getExperimentList(obj);
  if (res.rows.length) {
    setDatas(res.rows);
  }
  loading.value = false;
};
const handleCheckboxChange = (val) => {
  if (val) {
    taskSelectDialogRef.value.openDialog();
    const obj = editableTabs.value[Number(editableTabsValue.value)];
    obj.state = '待确认';
  }
};
const handleTaskSelectDialogSure = async (row) => {
  const obj = editableTabs.value[Number(editableTabsValue.value)];
  obj.taskForm.version = row.version;
  obj.taskForm.loadType = row.loadType;
  // obj.taskForm.loadExperimentName = row.loadExperimentName;
  obj.taskForm.stage = row.stage;
  await getpageVersions(obj.taskForm);
  obj.taskForm.loadcaseVersionId = row.loadcaseVersionId;
  obj.historyLoadExperimentId = row.id;
  oldExperimentData.value = row;
  obj.state = '待创建';
  if (obj.taskForm.loadExperimentName === row.loadExperimentName) {
    obj.taskForm.loadExperimentName = '';
    proxy?.$modal.msgWarning('任务名称与历史任务名称一致，请重新填写！');
  }
};
// const handleClickSure = async () => {
//   const obj = editableTabs.value[Number(editableTabsValue.value)];
//   obj.taskForm.loadType = obj.historyTaskForm.loadType;
//   obj.taskForm.stage = obj.historyTaskForm.stage;
//   obj.taskForm.version = obj.historyTaskForm.version;
//   await getpageVersions(obj.historyTaskForm);
//   obj.originalFileName = oldExperimentData.value.originalFileName;
//   obj.nodeInformationFileName = oldExperimentData.value.nodeInformationFileName;
//   obj.nodeLoadNumberFileName = oldExperimentData.value.nodeLoadNumberFileName;
//   obj.elevatorHingeCoordinateSystemInformation = oldExperimentData.value.elevatorHingeCoordinateSystemInformation;
//   obj.historyLoadExperimentId = oldExperimentData.value.id;
//   obj.taskForm.loadcaseVersionId = obj.historyTaskForm.loadcaseVersionId;
//   obj.state = '待创建';
// };
const handlePauseTask = async () => {
  const obj = editableTabs.value[Number(editableTabsValue.value)];
  const newObj = {
    id: obj.id,
    loadcaseVersionId: obj.taskForm.loadcaseVersionId,
    loadType: obj.taskForm.loadType,
    loadExperimentName: obj.taskForm.loadExperimentName,
    stage: obj.taskForm.stage,
    state: '已暂停'
  };
  await editExperiment(newObj);
};
const handleStopTask = async () => {
  const obj = editableTabs.value[Number(editableTabsValue.value)];
  const newObj = {
    id: obj.id,
    loadcaseVersionId: obj.taskForm.loadcaseVersionId,
    loadType: obj.taskForm.loadType,
    loadExperimentName: obj.taskForm.loadExperimentName,
    stage: obj.taskForm.stage,
    state: '已终止'
  };
  await editExperiment(newObj);
};
const handleRunLog = () => {
  const obj = editableTabs.value[Number(editableTabsValue.value)];
  runLogDialogRef.value.openDialog(obj.id);
};
onMounted(async () => {
  loading.value = true;
  await initData();
  await getPageLoadTypes();
  loading.value = false;
});
onUnmounted(() => {
  if (timer.value) {
    clearInterval(timer.value);
  }
});
onDeactivated(() => {
  if (timer.value) {
    clearInterval(timer.value);
  }
});
onActivated(async () => {
  loading.value = true;
  await initData();
  await getPageLoadTypes();
  loading.value = false;
});
</script>

<style lang="scss" scoped>
.task-block {
  border: 1px solid #e4e4e4;
  padding: 12px;
}
.block-title {
  font-size: 14px;
  font-weight: 600;
  padding-bottom: 12px;
}
</style>
